package com.alibaba.nacos.core.remote;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.ResolvableType;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RequestHandlerRegistry implements ApplicationListener<ContextRefreshedEvent> {

    Map<String, RequestHandler> registryHandlers = new HashMap<>();

    public RequestHandler getByRequestType(String requestType) {
        return registryHandlers.get(requestType);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        Map<String, RequestHandler> beansOfType = applicationContext.getBeansOfType(RequestHandler.class);
        for (Map.Entry<String, RequestHandler> entry : beansOfType.entrySet()) {
            RequestHandler requestHandler = entry.getValue();
            Class<?> requestType = ResolvableType.forInstance(requestHandler).as(RequestHandler.class).resolveGeneric(0);
            registryHandlers.putIfAbsent(requestType.getSimpleName(), requestHandler);
        }
    }
}
